//
//  SmallDecisionsCommonModalInteractiveTransition.m
//  SmallDecisions
//
//  Created by 李付雄 on 2025/6/14.
//

#import "SmallDecisionsCommonModalInteractiveTransition.h"
#import "SmallDecisionsNavigatorManager.h"
#import "SmallDecisionsBaseDefine.h"

@interface SmallDecisionsCommonModalInteractiveTransition()<CAAnimationDelegate>

@property (nonatomic, assign) BOOL isActive;
@property (nonatomic,   weak) UIViewController *viewController;
@property (nonatomic, strong) CAShapeLayer *maskLayer;

@property (nonatomic, assign) SmallDecisionsAnimationType type;

@end

@implementation SmallDecisionsCommonModalInteractiveTransition

- (void)addViewController:(UIViewController *)controller
                      type:(SmallDecisionsAnimationType)type {
    
    _viewController = controller;
    self.type       = type;
    
    UIPanGestureRecognizer *ges = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panHandle:)];
    [controller.view addGestureRecognizer:ges];
}

- (void)panHandle:(UIScreenEdgePanGestureRecognizer *)ges {
    
    [self popAnimationWithGes:ges];
}

- (void)popAnimationWithGes:(UIScreenEdgePanGestureRecognizer *)ges {
    
    CGFloat viewWidth = ges.view.frame.size.width;
    CGPoint point     = [ges translationInView:ges.view];
    CGFloat progress  = point.x / viewWidth;
        
    self.isActive = YES;
    UIGestureRecognizerState state = ges.state;
    switch (state) {
        case UIGestureRecognizerStateBegan: {
            
            [SmallDecisionsNavigatorManager interactiveDismissViewControllerAnimated:YES completion:nil];
        } break;
        case UIGestureRecognizerStateChanged: {
            
            [self updateInteractiveTransition:progress];
        } break;
            
        case UIGestureRecognizerStateEnded:
        case UIGestureRecognizerStateFailed:
        case UIGestureRecognizerStateCancelled: {
            
            if (progress >= 0.5) {
                
                [self finishInteractiveTransition];
                [SmallDecisionsNavigatorManager removeDismissViewController];
            } else {
                
                [self cancelInteractiveTransition];
            }
            self.isActive = NO;
        } break;
        default:
            break;
    }
}


@end
